package com.studyroom.service.impl;

import com.studyroom.dto.ChartDataDTO;
import com.studyroom.dto.StatisticsDTO;
import com.studyroom.entity.Order;
import com.studyroom.mapper.OrderMapper;
import com.studyroom.mapper.ReservationMapper;
import com.studyroom.mapper.UserMapper;
import com.studyroom.service.StatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class StatisticsServiceImpl implements StatisticsService {

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private ReservationMapper reservationMapper;

    @Override
    public StatisticsDTO getStatistics() {
        StatisticsDTO dto = new StatisticsDTO();
        
        dto.setTotalUsers(userMapper.selectCount(null));
        dto.setTodayOrders(orderMapper.countTodayOrders());
        dto.setTodayReservations(reservationMapper.countTodayReservations());
        dto.setTodayIncome(orderMapper.sumTodayIncome());
        
        return dto;
    }

    @Override
    public List<Map<String, Object>> getLatestReservations() {
        return reservationMapper.selectLatestReservations();
    }

    @Override
    public List<Order> getLatestOrders() {
        return orderMapper.selectLatestOrders();
    }

    @Override
    public ChartDataDTO getReservationStatistics() {
        List<Map<String, Object>> data = reservationMapper.selectReservationStatistics();
        return convertToChartData(data);
    }

    @Override
    public ChartDataDTO getIncomeStatistics() {
        List<Map<String, Object>> data = orderMapper.selectIncomeStatistics();
        return convertToChartData(data);
    }

    private ChartDataDTO convertToChartData(List<Map<String, Object>> data) {
        ChartDataDTO dto = new ChartDataDTO();
        List<String> xAxis = new ArrayList<>();
        List<Object> series = new ArrayList<>();
        
        // 获取最近7天的日期列表（包括今天）
        LocalDate today = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");
        Map<String, Object> valueMap = new HashMap<>();

        // 将数据转换为Map，直接使用数据库返回的日期格式
        for (Map<String, Object> item : data) {
            String dateStr = item.get("date").toString();
            valueMap.put(dateStr, item.get("value"));
        }

        // 生成最近7天的日期作为横坐标
        for (int i = 6; i >= 0; i--) {
            LocalDate date = today.minusDays(i);
            String formattedDate = date.format(formatter);
            xAxis.add(formattedDate);
            series.add(valueMap.getOrDefault(formattedDate, 0));
        }
        
        dto.setXAxis(xAxis);
        dto.setSeries(series);
        return dto;
    }
} 